/* eslint-disable func-names */
import axios from 'axios';
import service from './api';
import { getToken } from './token';


const instance = axios.create({
  baseURL: 'http://202.120.40.87:14642',
  timeout: 10000
});

// container of all request in this app
const Http = {};

Object.keys(service).forEach((key) => {
  const api = service[key];

  // assigment the request function to `Http` Object
  Http[key] = async function (
    params,
    isFormData = false,
    config = {},
    pathVariable = ''
  ) {
    let newParams = {};

    if (params && isFormData) {
      newParams = new FormData();
      Object.keys(params).forEach((i) => newParams.append(i, params[i]));
    } else {
      newParams = params;
    }
    let response = {};

    switch (api.method) {
      case 'put':
      case 'post':
      case 'patch':
        try {
          response = await instance[api.method](`${api.url}${pathVariable}`, newParams, config);
        } catch (err) {
          response = err.response;
        }
        break;
      case 'delete':
      case 'get':
        config.params = newParams;
        try {
          // response include {data:{ Result defined by ourself}, error:{}, status:{}, ...}
          response = await instance[api.method](`${api.url}${pathVariable}`, config);
        } catch (err) {
          // err.response include {data:{}, error:{}, status:{}, ...}
          response = err.response;
        }
        break;
      default:
        break;
    }
    // response include {data:{}, error:{}, status:{}, ...}
    return response;
  };
});

// add jwt to request if there is a token in asyncstorage
instance.interceptors.request.use(
  async (config) => {
    const token = await getToken();
    return token ? {
      ...config,
      headers: {
        ...config.headers,
        Authorization: token
      },
    } : config;
  },
  (err) => Promise.reject(err),
);


export default Http;
